function [HLS, HLS_hc] = GenerateHLSMap(params, max, varargin)
% Generate a HLS map
% params.th: preferred angle obtained by vector averaging, normalized to 0-1 
%       (result of e.g. CalcMapParams).
% params.mag: vector magnitude
% max: maximum value of dF images
%
% optional parameters
% 'ColorShift', value
% 'OutputPath', 'pathname' (in this case angle map will be saved)
% 'maxtuning', value - scale to max tuning value [0, 1]
%
% output is a HLS map whereas
% hue: preferred angle
% intensity: max_change
% saturation: tune (0-tune_max)
%
% HLS_hc: high contrast HLS map

colorShift = 60/360; % this gives blue as horizontal orientation, assuming that the hue_table starts with red by default
pathname = [];
highcontrast = 0;
tune_max = 1;

% process optional parameters
if ~isempty(varargin)
    numIndex = find(cellfun('isclass', varargin(1:end-1), 'char'));
    for ind = 1:length(numIndex)
        switch lower(varargin{numIndex(ind)})
            case 'colorshift'
                colorShift = varargin{numIndex(ind) + 1};
            case 'outputpath'
                pathname = varargin{numIndex(ind) + 1};
            case 'maxtuning' % should be [0, 1]
                tune_max = varargin{numIndex(ind) + 1};
        end
    end
end

dim = size(params.th);
HLS = zeros(dim(1),dim(2),3);
HLS_hc = zeros(dim(1),dim(2),3);

params.th = mod(params.th + colorShift, 1 );
if (max > 0)
    for x = 1:dim(1)
        for y = 1:dim(2)
            m1 = params.max_change(x,y) ./ max;
            m2 = params.max_change(x,y) * 2 ./ max;
            s = params.tune(x,y) ./ tune_max;
            if m1 > 1; m1 = 1; end;
            if m2 > 1; m2 = 1; end;
            if s > 1; s = 1; end;
            HLS(x,y,:) = HsvToRgb(params.th(x,y),s,m1)';
            HLS_hc(x,y,:) = HsvToRgb(params.th(x,y),s,m2)';
            %         HLS(x,y,:) = hsv2rgb([params.th(x,y),s,m1]);
            %         HLS_hc(x,y,:) = hsv2rgb([params.th(x,y),s,m2]);
        end
    end
end

if ~isempty(pathname)
    imwrite(HLS, fullfile(pathname, 'HLS.tif'));
    imwrite(HLS_hc, fullfile(pathname, 'HLS_hc.tif'));
end